<template>
  <div class="become-seller-container">
    <div class="header-section">
      <h1 class="page-title">成为商家</h1>
      <p class="page-subtitle">加入我们的商家平台，开启您的电商之旅</p>
    </div>

    <!-- 已是商家提示 -->
    <div v-if="isAlreadySeller" class="already-seller-notice">
      <div class="notice-card">
        <div class="notice-icon">
          <i class="icon-check-circle"></i>
        </div>
        <div class="notice-content">
           <h3>{{ sellerNoticeTitle }}</h3>
           <p>{{ sellerNoticeMessage }}</p>
           <div class="notice-actions">
             <button @click="goToSellerLogin" class="btn-primary">
               前往商家登录
             </button>
             <button @click="goToHome" class="btn-secondary">
               返回首页
             </button>
           </div>
         </div>
      </div>
    </div>

    <div v-else class="form-container">
      <div class="form-card">
        <div class="card-header">
          <h2>商家入驻申请</h2>
          <p>请填写以下信息完成商家入驻申请</p>
        </div>

        <form @submit.prevent="submitApplication" class="seller-form">
          <!-- 店铺名称 -->
          <div class="form-group">
            <label for="shopName" class="form-label">
              <span class="required">*</span>店铺名称
            </label>
            <input
              id="shopName"
              v-model="formData.shopName"
              type="text"
              class="form-input"
              placeholder="请输入您的店铺名称"
              required
              maxlength="50"
            />
            <div class="form-hint">店铺名称将作为您在平台上的展示名称</div>
          </div>

          <!-- 联系人 -->
          <div class="form-group">
            <label for="contactPerson" class="form-label">
              <span class="required">*</span>联系人
            </label>
            <input
              id="contactPerson"
              v-model="formData.contactPerson"
              type="text"
              class="form-input"
              placeholder="请输入联系人姓名"
              required
              maxlength="20"
            />
          </div>

          <!-- 联系电话 -->
          <div class="form-group">
            <label for="contactPhone" class="form-label">
              <span class="required">*</span>联系电话
            </label>
            <input
              id="contactPhone"
              v-model="formData.contactPhone"
              type="tel"
              class="form-input"
              placeholder="请输入联系电话"
              required
              pattern="^1[3-9]\d{9}$"
            />
            <div class="form-hint">请输入有效的手机号码</div>
          </div>

          <!-- 地址 -->
          <div class="form-group">
            <label for="address" class="form-label">
              <span class="required">*</span>店铺地址
            </label>
            <textarea
              id="address"
              v-model="formData.address"
              class="form-textarea"
              placeholder="请输入详细的店铺地址"
              required
              maxlength="200"
              rows="3"
            ></textarea>
          </div>

          <!-- Logo上传 -->
          <div class="form-group">
            <label class="form-label">
              <span class="required">*</span>店铺Logo
            </label>
            <div class="logo-upload-section">
              <div class="logo-preview" v-if="logoPreview">
                <img :src="logoPreview" alt="Logo预览" class="logo-image" />
                <button type="button" @click="removeLogo" class="remove-logo-btn">
                  ×
                </button>
              </div>
              <div v-else class="logo-upload-placeholder">
                <input
                  ref="logoInput"
                  type="file"
                  accept="image/*"
                  @change="handleLogoUpload"
                  class="logo-input"
                  hidden
                />
                <div class="upload-area" @click="$refs.logoInput.click()">
                  <div class="upload-icon">📷</div>
                  <div class="upload-text">点击上传Logo</div>
                  <div class="upload-hint">支持 JPG、PNG 格式，建议尺寸 200x200px</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="form-actions">
            <button
              type="submit"
              class="submit-btn"
              :disabled="isSubmitting || !isFormValid"
              :class="{ loading: isSubmitting }"
            >
              <span v-if="isSubmitting">提交中...</span>
              <span v-else>提交申请</span>
            </button>
          </div>
        </form>
      </div>

      <!-- 申请须知 -->
      <div class="info-card">
        <h3>申请须知</h3>
        <ul class="info-list">
          <li>请确保提供的信息真实有效</li>
          <li>店铺Logo将用于商品展示和店铺页面</li>
          <li>联系信息将用于平台与您的沟通</li>
          <li>申请提交后，我们将在1-3个工作日内审核</li>
          <li>审核通过后，您将收到商家账号开通通知</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { addSeller, uploadLogo } from '@/api/seller'

export default {
  name: 'BecomeSeller',
  data() {
    return {
      formData: {
        shopName: '',
        contactPerson: '',
        contactPhone: '',
        address: '',
        logoUrl: ''
      },
      logoPreview: null,
      logoFile: null,
      isSubmitting: false,
      isAlreadySeller: false,
      justSubmittedApplication: false
    }
  },
  mounted() {
    this.checkSellerStatus()
  },
  computed: {
    isFormValid() {
      return (
        this.formData.shopName.trim() &&
        this.formData.contactPerson.trim() &&
        this.formData.contactPhone.trim() &&
        this.formData.address.trim() &&
        this.formData.logoUrl
      )
    },
    sellerNoticeTitle() {
      return this.justSubmittedApplication ? '申请提交成功！' : '您已经是商家了！'
    },
    sellerNoticeMessage() {
      return this.justSubmittedApplication 
        ? '您的商家入驻申请已成功提交，我们将在1-3个工作日内审核您的申请。审核通过后，您就可以登录商家管理系统了。'
        : '您的账户已具有商家权限，可以直接登录商家管理系统'
    }
  },
  methods: {
    // 检查用户是否已经是商家
    checkSellerStatus() {
      try {
        // 检查localStorage中的用户信息
        const userInfo = localStorage.getItem('userInfo')
        const userRoles = localStorage.getItem('userRoles')
        const sellerToken = localStorage.getItem('sellerToken')
        
        if (userInfo) {
          const user = JSON.parse(userInfo)
          
          // 检查登录返回的角色数据结构
          if (user.roles && Array.isArray(user.roles)) {
            // 检查角色对象数组中是否有商家角色
            const hasSellerRole = user.roles.some(role => {
              return role.code === 'SELLER' || role.name === '商家' || 
                     role.code === 'seller' || role.name === 'seller'
            })
            if (hasSellerRole) {
              this.isAlreadySeller = true
              return
            }
          }
          
          // 兼容旧的字符串数组格式
          if (user.roles && user.roles.includes && user.roles.includes('seller')) {
            this.isAlreadySeller = true
            return
          }
        }
        
        if (userRoles) {
          const roles = JSON.parse(userRoles)
          
          // 检查角色数组，支持对象数组和字符串数组两种格式
          if (Array.isArray(roles)) {
            const hasSellerRole = roles.some(role => {
              if (typeof role === 'object' && role !== null) {
                return role.code === 'SELLER' || role.name === '商家' || 
                       role.code === 'seller' || role.name === 'seller'
              } else {
                return role === 'seller' || role === 'SELLER' || role === '商家'
              }
            })
            if (hasSellerRole) {
              this.isAlreadySeller = true
              return
            }
          }
        }
        
        // 检查是否有商家token
        if (sellerToken) {
          this.isAlreadySeller = true
          return
        }
        
        this.isAlreadySeller = false
      } catch (error) {
        console.error('检查商家状态失败:', error)
        this.isAlreadySeller = false
      }
    },

    // 跳转到商家登录页面
    goToSellerLogin() {
      this.$router.push('/seller-login')
    },

    // 返回首页
    goToHome() {
      this.$router.push('/')
    },

    // 处理Logo上传
    async handleLogoUpload(event) {
      const file = event.target.files[0]
      if (!file) return

      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        this.$message?.error('请选择图片文件')
        return
      }

      // 验证文件大小 (2MB)
      if (file.size > 2 * 1024 * 1024) {
        this.$message?.error('图片大小不能超过2MB')
        return
      }

      this.logoFile = file

      // 创建预览
      const reader = new FileReader()
      reader.onload = (e) => {
        this.logoPreview = e.target.result
      }
      reader.readAsDataURL(file)

      // 上传到服务器
      await this.uploadLogoToServer()
    },

    // 上传Logo到服务器
    async uploadLogoToServer() {
      if (!this.logoFile) return

      try {
        const response = await uploadLogo(this.logoFile)

        // 后端直接返回字符串URL
        if (typeof response === 'string' && response.startsWith('http')) {
          this.formData.logoUrl = response
          console.log('Logo上传成功，URL:', response)
        } else if (response.code === '200') {
          // 兼容包装格式的响应
          this.formData.logoUrl = response.data
          console.log('Logo上传成功，URL:', response.data)
        } else {
          throw new Error(response.info || 'Logo上传失败')
        }
      } catch (error) {
        console.error('Logo上传失败:', error)
        alert('Logo上传失败，请重试')
        this.removeLogo()
      }
    },

    // 移除Logo
    removeLogo() {
      this.logoPreview = null
      this.logoFile = null
      this.formData.logoUrl = ''
      if (this.$refs.logoInput) {
        this.$refs.logoInput.value = ''
      }
    },

    // 提交申请
    async submitApplication() {
      if (!this.isFormValid) {
        alert('请填写完整的申请信息')
        return
      }

      this.isSubmitting = true

      try {
        await addSeller({
          shopName: this.formData.shopName.trim(),
          contactPerson: this.formData.contactPerson.trim(),
          contactPhone: this.formData.contactPhone.trim(),
          address: this.formData.address.trim(),
          logoUrl: this.formData.logoUrl
        })

        // 直接当作成功处理，不检查响应
        alert('申请提交成功！我们将在1-3个工作日内审核您的申请')
        
        // 将页面状态改为已是商家状态
        this.isAlreadySeller = true
        this.justSubmittedApplication = true
        
        // 可以选择性地更新localStorage中的用户角色信息
        this.updateUserRoleToSeller()
        
        // 重置表单
        this.resetForm()
      } catch (error) {
        console.error('申请提交失败:', error)
        alert('申请提交失败，请重试')
      } finally {
        this.isSubmitting = false
      }
    },

    // 更新用户角色为商家
    updateUserRoleToSeller() {
      try {
        // 更新userInfo中的角色
        const userInfo = localStorage.getItem('userInfo')
        if (userInfo) {
          const user = JSON.parse(userInfo)
          if (!user.roles) {
            user.roles = []
          }
          
          // 检查是否已经有商家角色
          const hasSellerRole = user.roles.some(role => {
            if (typeof role === 'object' && role !== null) {
              return role.code === 'SELLER' || role.name === '商家'
            } else {
              return role === 'seller' || role === 'SELLER'
            }
          })
          
          // 如果没有商家角色，添加一个
          if (!hasSellerRole) {
            user.roles.push({
              id: 13,
              name: '商家',
              code: 'SELLER'
            })
            localStorage.setItem('userInfo', JSON.stringify(user))
          }
        }

        // 更新userRoles
        const userRoles = localStorage.getItem('userRoles')
        if (userRoles) {
          const roles = JSON.parse(userRoles)
          
          // 检查是否已经有商家角色
          const hasSellerRole = roles.some(role => {
            if (typeof role === 'object' && role !== null) {
              return role.code === 'SELLER' || role.name === '商家'
            } else {
              return role === 'seller' || role === 'SELLER' || role === '商家'
            }
          })
          
          if (!hasSellerRole) {
            roles.push({
              id: 13,
              name: '商家',
              code: 'SELLER'
            })
            localStorage.setItem('userRoles', JSON.stringify(roles))
          }
        } else {
          // 如果没有userRoles，创建一个包含seller角色对象的数组
          localStorage.setItem('userRoles', JSON.stringify([{
            id: 13,
            name: '商家',
            code: 'SELLER'
          }]))
        }
      } catch (error) {
        console.error('更新用户角色失败:', error)
      }
    },

    // 重置表单
    resetForm() {
      this.formData = {
        shopName: '',
        contactPerson: '',
        contactPhone: '',
        address: '',
        logoUrl: ''
      }
      this.removeLogo()
    }
  }
}
</script>

<style scoped>
.become-seller-container {
  width: 100%;
  max-width: none;
  margin: 0;
  overflow-y: auto;
  max-height: 100vh;
  padding: 40px;
  background-color: #f8f9fa;
}

.header-section {
  text-align: center;
  margin-bottom: 40px;
  padding: 40px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 10px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 0;
}

.form-container {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
  align-items: start;
}

@media (max-width: 768px) {
  .form-container {
    grid-template-columns: 1fr;
  }
}

.form-card, .info-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e9ecef;
}

.card-header {
  margin-bottom: 30px;
  text-align: center;
}

.card-header h2 {
  color: #2c3e50;
  font-size: 1.5rem;
  margin-bottom: 8px;
}

.card-header p {
  color: #6c757d;
  margin: 0;
}

.form-group {
  margin-bottom: 24px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #2c3e50;
  font-size: 0.95rem;
}

.required {
  color: #e74c3c;
  margin-right: 4px;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-size: 0.95rem;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.form-hint {
  font-size: 0.85rem;
  color: #6c757d;
  margin-top: 4px;
}

.logo-upload-section {
  border: 2px dashed #dee2e6;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  transition: border-color 0.3s ease;
}

.logo-upload-section:hover {
  border-color: #667eea;
}

.logo-preview {
  position: relative;
  display: inline-block;
}

.logo-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 8px;
  border: 2px solid #e9ecef;
}

.remove-logo-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #e74c3c;
  color: white;
  border: none;
  cursor: pointer;
  font-size: 16px;
  line-height: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-area {
  cursor: pointer;
  padding: 20px;
  transition: background-color 0.3s ease;
}

.upload-area:hover {
  background-color: #f8f9fa;
}

.upload-icon {
  font-size: 2rem;
  margin-bottom: 10px;
}

.upload-text {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 5px;
}

.upload-hint {
  font-size: 0.85rem;
  color: #6c757d;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 14px 40px;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 140px;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.submit-btn.loading {
  position: relative;
}

.info-card h3 {
  color: #2c3e50;
  margin-bottom: 20px;
  font-size: 1.2rem;
}

.info-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.info-list li {
  padding: 8px 0;
  border-bottom: 1px solid #f1f3f4;
  color: #495057;
  position: relative;
  padding-left: 20px;
}

.info-list li:before {
  content: '•';
  color: #667eea;
  font-weight: bold;
  position: absolute;
  left: 0;
}

.info-list li:last-child {
  border-bottom: none;
}

/* 已是商家提示样式 */
.already-seller-notice {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
}

.notice-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 40px;
  max-width: 600px;
  width: 100%;
  color: white;
  text-align: center;
  box-shadow: 0 20px 40px rgba(102, 126, 234, 0.3);
  position: relative;
  overflow: hidden;
}

.notice-card::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
  animation: shimmer 3s ease-in-out infinite;
}

@keyframes shimmer {
  0%, 100% { transform: rotate(0deg); }
  50% { transform: rotate(180deg); }
}

.notice-icon {
  font-size: 4rem;
  margin-bottom: 20px;
  position: relative;
  z-index: 1;
}

.icon-check-circle::before {
  content: '✓';
  display: inline-block;
  width: 80px;
  height: 80px;
  line-height: 80px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  border: 3px solid rgba(255, 255, 255, 0.3);
}

.notice-content {
  position: relative;
  z-index: 1;
}

.notice-content h3 {
  font-size: 2rem;
  margin-bottom: 15px;
  font-weight: 700;
}

.notice-content p {
  font-size: 1.1rem;
  margin-bottom: 30px;
  opacity: 0.9;
  line-height: 1.6;
}

.notice-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

.notice-actions .btn-primary,
.notice-actions .btn-secondary {
  padding: 12px 30px;
  border-radius: 25px;
  font-weight: 600;
  font-size: 1rem;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 140px;
}

.notice-actions .btn-primary {
  background: rgba(255, 255, 255, 0.9);
  color: #667eea;
}

.notice-actions .btn-primary:hover {
  background: white;
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

.notice-actions .btn-secondary {
  background: transparent;
  color: white;
  border: 2px solid rgba(255, 255, 255, 0.5);
}

.notice-actions .btn-secondary:hover {
  background: rgba(255, 255, 255, 0.1);
  border-color: white;
  transform: translateY(-2px);
}

@media (max-width: 768px) {
  .notice-card {
    padding: 30px 20px;
    margin: 0 20px;
  }
  
  .notice-content h3 {
    font-size: 1.5rem;
  }
  
  .notice-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .notice-actions .btn-primary,
  .notice-actions .btn-secondary {
    width: 100%;
    max-width: 200px;
  }
}
</style>